import { inject, ref, computed } from 'vue';
import Utils from '@/utils/utils';

// 退出位置
export function useExitPosition({ articleRef, articleData }) {
  const rootRef = inject('rootRef');
  // const exitPosition = ref('0%');
  const exitPosition = ref(0);
  const { height: windowHeight } = document.body.getBoundingClientRect();

  function getPosition() {
    const { height: articleHeight } = articleRef.value.getBoundingClientRect();
    if (articleHeight <= windowHeight) {
      exitPosition.value = 100;
    } else {
      let val = (windowHeight + rootRef.value.scrollTop) / articleHeight;
      exitPosition.value = `${((val > 1 ? 1 : val) * 100) >>> 0}`;
    }
    return exitPosition.value;
  }

  return getPosition;
}

// 音视频 播放进度
export function usePercentage() {
  const videoTime = ref(0);
  const audioTime = ref(0);

  let nodeName = '';

  // 监听函数
  const timeupdateHandler = Utils.throttle(
    (event) => {
      if (nodeName !== event.target.nodeName) {
        nodeName = event.target.nodeName;
      }
      if (event.target.nodeName === 'AUDIO') {
        audioTime.value += 1;
      } else {
        videoTime.value += 1;
      }
    },
    1000,
    true
  );

  let doms = null;
  function getDom() {
    if (doms) return doms;
    let videoDoms = document.querySelectorAll(`[xlt-video]`);
    let audioDoms = document.querySelectorAll(`[xlt-audio]`);
    doms = [...videoDoms, ...audioDoms];
    return doms;
  }

  function startListener() {
    getDom().forEach((dom) => {
      dom.addEventListener('timeupdate', timeupdateHandler, false);
    });
  }

  function removeListener() {
    doms = null;
    getDom().forEach((dom) => {
      dom.removeEventListener('timeupdate', timeupdateHandler, false);
    });
  }

  function resetListener() {
    doms = null;
    videoTime.value = 0;
    audioTime.value = 0;

    startListener();
  }

  function getVideoPercentage() {
    // 视频总时长
    let videoTotalTime =
      Array.from(document.querySelectorAll(`[xlt-video]`)).reduce(
        (total, item) => (total += item.duration),
        0
      ) || 0;
    if (videoTime.value > videoTotalTime) {
      videoTime.value = videoTotalTime;
    }
    let percentage = (videoTime.value / videoTotalTime) * 100;
    return {
      videoTime,
      videoTotalTime,
      percentage: `${percentage >> 0}`
    };
  }

  function getAudioPercentage() {
    // 音频总时长
    let audioTotalTime =
      Array.from(document.querySelectorAll(`[xlt-audio]`)).reduce(
        (total, item) => (total += item.duration),
        0
      ) || 0;

    if (audioTime.value > audioTotalTime) {
      audioTime.value = audioTotalTime;
    }

    let percentage = (audioTime.value / audioTotalTime) * 100;

    return {
      audioTime,
      audioTotalTime,
      percentage: `${percentage >> 0}`
    };
  }

  return {
    getVideoPercentage,
    getAudioPercentage,
    startListener,
    removeListener,
    resetListener
  };
}

// 音视频埋点
export function useMediaPoint() {
  // 是否播放
  let isPlay = ref(false);
  // 首次播放时间
  let firstPlayTime = ref(null);
  // 音频播放时长 s
  let audioPlayTime = ref(0);
  // 视频播放时长 s
  let videoPlayTime = ref(0);

  // 媒体映射
  let MEDIA = {
    AUDIO: audioPlayTime,
    VIDEO: videoPlayTime
  };

  let mediaDoms = null;
  function getMediaDom() {
    if (mediaDoms) return mediaDoms;
    const videoDoms = document.querySelectorAll(`[xlt-video]`);
    const audioDoms = document.querySelectorAll(`[xlt-audio]`);
    mediaDoms = [...videoDoms, ...audioDoms];
    return mediaDoms;
  }

  function play() {
    if (!firstPlayTime.value) {
      firstPlayTime.value = Utils.date2string(null, '-', true);
    }

    isPlay.value = true;
  }

  function pause() {
    isPlay.value = false;
  }

  const timeupdate = Utils.throttle(
    (event) => {
      MEDIA[event.target.nodeName].value += 1;
      console.log('timeupdate -> ', MEDIA[event.target.nodeName].value);
    },
    1000,
    true
  );

  function reset() {
    isPlay.value = false;
    firstPlayTime.value = null;
    audioPlayTime.value = 0;
    videoPlayTime.value = 0;
    mediaDoms = null;
  }

  function start() {
    getMediaDom().forEach((dom) => {
      dom.addEventListener('play', play, false);
      dom.addEventListener('pause', pause, false);
      dom.addEventListener('timeupdate', timeupdate, false);
    });
  }

  function remove() {
    getMediaDom().forEach((dom) => {
      dom.removeEventListener('play', play, false);
      dom.removeEventListener('pause', pause, false);
      dom.removeEventListener('timeupdate', timeupdate, false);
    });
  }

  function getVideoTotalTime() {
    return (
      Array.from(document.querySelectorAll(`[xlt-video]`)).reduce(
        (total, item) => (total += item.duration),
        0
      ) || 0
    );
  }

  function getAudioTotalTime() {
    return (
      Array.from(document.querySelectorAll(`[xlt-audio]`)).reduce(
        (total, item) => (total += item.duration),
        0
      ) || 0
    );
  }

  function getVideoTime() {
    if (videoPlayTime.value > getVideoTotalTime()) {
      return getVideoTotalTime();
    }
    return videoPlayTime.value;
  }

  function getAudioTime() {
    if (audioPlayTime.value > getAudioTotalTime()) {
      return getAudioTotalTime();
    }
    return audioPlayTime.value;
  }

  // 获取播放时间
  function getPlayTime() {
    let mediaTime = Math.max(getVideoTime(), getAudioTime());
    let leaveTime = new Date(Utils.iosTime(firstPlayTime.value)).setMilliseconds(mediaTime * 1000);
    console.log('mediaTime->', mediaTime, leaveTime);
    return {
      inTime: firstPlayTime.value,
      leaveTime: Utils.date2string(leaveTime, '-', true)
    };
  }

  // 获取百分比
  function getPercentage() {
    let videoPercentage = (getVideoTime() / getVideoTotalTime()) * 100;
    let audioPercentage = (getAudioTime() / getAudioTotalTime()) * 100;
    return {
      video: videoPercentage >> 0,
      audio: audioPercentage >> 0
    };
  }

  return {
    start,
    remove,
    reset,
    isPlay,
    getPercentage,
    getPlayTime
  };
}
